package com.yc.utils;


import cn.hutool.core.lang.Snowflake;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class SnowflakeIdGenerator {
    // 注入Snowflake ID生成器
    @Autowired
    private Snowflake snowflake;

    public SnowflakeIdGenerator() {
        // 配置 Snowflake ID Generator
        // 注意 workerId 和 datacenterId 要根据实际情况进行调整
        this.snowflake = new Snowflake(1, 1);  // workerId 和 datacenterId
    }


    // 生成一个ID
    public synchronized long nextId() {
        return snowflake.nextId();
    }

    /**
     * 批量生成ID
     * 最大1000
     * @param size
     * @return
     */
    private final int batchMaxSize = 1000;
    public  List<Long> nextIdBatch(int size) {
        if (size > batchMaxSize) {
            size = batchMaxSize;
        }
        List<Long> list = new ArrayList<>();
        for (int i = 0; i < size; i++) {
            list.add(  nextId()  );
        }
        return list;
    }

    /**
     *  解析时间戳
     */
    public long parseIdToTime(long id) {
        return snowflake.getGenerateDateTime( id );
    }
    /**
     *  解析数据中心ID
     */
    public long parseIdToDatacenterId(long id) {
        return snowflake.getDataCenterId(id );
    }
    /**
     *  解析workerId
     */
    public long parseIdToWorkerId(long id) {
        return snowflake.getWorkerId( id );
    }
}

